package com.example.za.account.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.za.account.R;
import com.example.za.account.activity.CategoryActivity;
import com.example.za.account.adapter.GridExpCatAdapter;
import com.example.za.account.adapter.GridInCatAdapter;
import com.example.za.account.application.AccountApplication;
import com.example.za.account.dao.ExpenseCatDao;
import com.example.za.account.dao.ExpenseDao;
import com.example.za.account.model.Expense;
import com.example.za.account.model.ExpenseCat;
import com.example.za.account.utils.Constant;
import com.example.za.account.utils.DateUtils;
import com.example.za.account.utils.T;

import org.greenrobot.eventbus.EventBus;

import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class ExpenseFragment extends BaseFragment implements AdapterView.OnItemClickListener {

    @BindView(R.id.et_expense)
    EditText etExpense;
    @BindView(R.id.icon_expense_cat)
    ImageView iconExpenseCat;
    @BindView(R.id.label_expense_cat)
    TextView labelExpenseCat;
    @BindView(R.id.ll_expense_cat)
    LinearLayout llExpenseCat;
    @BindView(R.id.label_expense_time)
    TextView labelExpenseTime;
    @BindView(R.id.et_expense_note)
    EditText etExpenseNote;
    Unbinder unbinder;
    private View rootView;
    private static final int REQUEST_ADD_CATEGORY = 0x201;
    private static final int REQUEST_UPDATE_CATEGORY = 0x202;
    private boolean mIsUpdateCat;
    private ExpenseCatDao mExpenseCatDao;
    private Date mDate;
    private Expense mExpense;
    private PopupWindow mPopupWindow;
    private onTimePickListener mOnTimePickListener;
    private boolean mIsUpdateExpense;
    private GridExpCatAdapter mCatAdapter;
    private Context mContext;

    public static ExpenseFragment getInstance(Expense expense) {
        Bundle bundle = new Bundle();
        bundle.putParcelable(Constant.RECORD, expense);
        ExpenseFragment expenseFragment = new ExpenseFragment();
        expenseFragment.setArguments(bundle);
        return expenseFragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof onTimePickListener) {
            mOnTimePickListener = (onTimePickListener) activity;
        }
        mContext = activity;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = super.onCreateView(inflater, container, savedInstanceState);
            unbinder = ButterKnife.bind(this, rootView);
            mExpenseCatDao = new ExpenseCatDao(mContext);
            mCatAdapter = new GridExpCatAdapter(mContext, getCategory());
            Bundle arguments = getArguments();
            if (arguments != null) {
                mIsUpdateExpense = true;
                mExpense = arguments.getParcelable(Constant.RECORD);
                etExpenseNote.setText(mExpense.getmNote());
                etExpense.setText(String.valueOf(mExpense.getmAmount()));
                iconExpenseCat.setImageResource(mExpense.getmCategory().getmImageId());
                labelExpenseCat.setText(mExpense.getmCategory().getmName());
                mDate = mExpense.getmDate();
            } else {
                mIsUpdateExpense = false;
                mDate = new Date();
                mExpense = new Expense();
                mExpense.setmUser(AccountApplication.sUser);
                mExpense.setmDate(mDate);
                mExpense.setmCategory((ExpenseCat) mCatAdapter.getItem(0));
            }
            labelExpenseTime.setText(DateUtils.date2Str(mDate));

            //绘制弹出页的界面
            LinearLayout linearLayout = (LinearLayout) getActivity().getLayoutInflater().inflate(R.layout.pop_category, null);
            GridView gridExpenseCat = (GridView) linearLayout.findViewById(R.id.grid_category);
            gridExpenseCat.setOnItemClickListener(this);
            gridExpenseCat.setAdapter(mCatAdapter);
            //为类别图标设置点击监听事件，点击的时候设置账目的类别
            gridExpenseCat.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (mCatAdapter.getCloseVisibility() == View.VISIBLE) {
                        mCatAdapter.setCloseVisibility(View.GONE);
                    }
                    return false;
                }
            });

            //为类别图标设置长按监听事件，长按的时候进入修改类别的界面
            gridExpenseCat.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                    ExpenseCat expenseCat = (ExpenseCat) mCatAdapter.getItem(position);
                    Intent intent = new Intent(mContext, CategoryActivity.class);
                    intent.putExtra(Constant.UPDATE_CAT, expenseCat);
                    startActivityForResult(intent, REQUEST_UPDATE_CATEGORY);
                    return true;
                }
            });

            //创建弹出式对话框，让用户管理收支类别
            mPopupWindow = new PopupWindow(linearLayout, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT, true);
            mPopupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
            mPopupWindow.setAnimationStyle(R.style.popwindow_anim_style);

        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
    }

    @Override
    protected Fragment getSubFragment() {
        return this;
    }

    @Override
    protected int getResId() {
        return R.layout.fragment_expense;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (mIsUpdateCat && mCatAdapter != null) {
            mCatAdapter.setData(getCategory());
        }
    }

    private List<ExpenseCat> getCategory() {
        List<ExpenseCat> cats = mExpenseCatDao.getExpenseCat((AccountApplication.sUser.getmId()));
        cats.add(new ExpenseCat(R.drawable.jiahao_bai, "添加", AccountApplication.sUser));
        cats.add(new ExpenseCat(R.drawable.jianhao_bai, "删除", AccountApplication.sUser));
        return cats;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            mIsUpdateCat = requestCode == REQUEST_ADD_CATEGORY || requestCode == REQUEST_UPDATE_CATEGORY;
        } else {
            mIsUpdateCat = false;
        }
    }

    @OnClick({R.id.ll_expense_cat, R.id.label_expense_time, R.id.btn_expense_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_expense_cat:
                if (mPopupWindow.isShowing()) {
                    mPopupWindow.dismiss();
                } else {
                    mPopupWindow.showAsDropDown(llExpenseCat);
                }
                break;
            case R.id.label_expense_time: {
                if (mOnTimePickListener != null) {
                    mOnTimePickListener.DisplayDialog(mDate);
                }
            }
            break;
            case R.id.btn_expense_save:
                saveExpense();
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ExpenseCat expenseCat = (ExpenseCat) parent.getItemAtPosition(position);
        if (expenseCat.getmImageId() == R.drawable.jiahao_bai) {
            Intent intent = new Intent(mContext, CategoryActivity.class);
            intent.putExtra(Constant.TYPE_CATEGORY, Constant.TYPE_EXPENSE);
            startActivityForResult(intent, REQUEST_ADD_CATEGORY);
        } else if (expenseCat.getmImageId() == R.drawable.jianhao_bai) {
            mCatAdapter.setCloseVisibility(View.VISIBLE);
        } else {
            mExpense.setmCategory(expenseCat);
            iconExpenseCat.setImageResource(expenseCat.getmImageId());
            labelExpenseCat.setText(expenseCat.getmName());
            mPopupWindow.dismiss();
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mOnTimePickListener = null;
    }

    public void setDate(Date date) {
        mExpense.setmDate(date);
        labelExpenseTime.setText(DateUtils.date2Str(date));
    }

    private void saveExpense() {
        String trim = etExpense.getText().toString().trim();
        if (TextUtils.isEmpty(trim)) {
            Toast.makeText(mContext, "请输入金额", Toast.LENGTH_SHORT).show();
            return;
        }
        float amount = Float.parseFloat(trim);
        String note = etExpenseNote.getText().toString().trim();
        mExpense.setmAmount(amount);
        mExpense.setmNote(note);
        ExpenseDao expenseDao = new ExpenseDao(mContext);
        if (mIsUpdateExpense) {
            if (expenseDao.updateExpense(mExpense)) {
                T.showShort(mContext, "修改成功");
                EventBus.getDefault().post("expense_updated");
                getActivity().finish();
            } else {
                T.showShort(mContext, "修改失败");
            }
        } else {
            if (expenseDao.addExpense(mExpense)) {
                T.showShort(mContext, "保存成功");
                EventBus.getDefault().post("expense_inserted");
                getActivity().finish();
            } else {
                T.showShort(mContext, "保存失败");
            }
        }
    }

    public interface onTimePickListener {
        void DisplayDialog(Date date);
    }


}
